package com.hghivln.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hghivln.blog.common.exception.BlogException;
import com.hghivln.blog.entity.SysUser;
import com.hghivln.blog.entity.User;
import com.hghivln.blog.mapper.UserMapper;
import com.hghivln.blog.pojo.dto.UpdatePwdDto;
import com.hghivln.blog.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hghivln.blog.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author hghivln
 * @since 2021-09-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private IdWorker idWorker;

    @Override
    public User getByUsername(String username) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username",username);
        return getBaseMapper().selectOne(qw);
    }

    @Override
    public void updatePwd(UpdatePwdDto updatePwdDto) {
        User user = getBaseMapper().selectById(updatePwdDto.getId());
        if (!user.getPassword().equals(updatePwdDto.getCurrentPwd())){
            throw new BlogException("当前的密码不正确");
        }
        getBaseMapper().updatePwd(updatePwdDto);
    }

    @Override
    public boolean updateById(User entity) {
        try {
            getBaseMapper().updateById(entity);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean save(User entity) {
        entity.setUserId(idWorker.nextId());
        if (entity.getSex().equals(1)){
            entity.setHeader("http://42.194.192.60:8888/group1/M00/00/00/rBAAD2FU6SiAcR2iAAAICB0wRZc701.png");
            //entity.setHeader("http://42.194.192.60:8888/group1/M00/00/00/rBAAD2FPX_qAFEVdAAB7kwXiDK074.jpeg");
        }else {
            entity.setHeader("http://42.194.192.60:8888/group1/M00/00/00/rBAAD2FU6W-AeRvCAACm43tZUtg282.png");
            //entity.setHeader("http://42.194.192.60:8888/group1/M00/00/00/rBAAD2FPX7aAOEiVAAAUA04n0ps467.png");
        }
        getBaseMapper().insert(entity);
        return true;
    }
}
